package com.northpool.operator.dataset.index;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datatable.operate.ITableOperator;

import java.util.concurrent.TimeUnit;

@OperatorInfo(
        ref = "TableCreateIndexOperator",
        version = "0.0.1",
        name = "创建主键",
        description = "数据表创建索引"
)
public class TableCreateIndexOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "datasource", name = "数据源", desc = "数据源ID"),
            @InputParam(ref = "tableName", name = "表名称", desc = "数据表名称，如: tb_test"),
            @InputParam(ref = "field", name = "主键字段", desc = "需要创建的主键字段名称，如: kid"),
    })
    public TableCreateIndexOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(TableCreateIndexOperator.class,
                TestParamBuilder.aBuilder()
                        .param("datasource", "test_bcg")
                        .param("tableName", "bj_landuse")
                        .param("field", "gid")
                        .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String datasource = paramTool.getStr("datasource");
        String dataSourceJson = DatabaseUtils.getDataSourceJson(datasource);
        String tableName = paramTool.getStr("tableName");
        String field = paramTool.getStr("field");
        IDataSource ds = IDataSource.fromJSON(dataSourceJson);
        ITableOperator tableOperator = ds.getTableOperator(tableName);
        tableOperator.createPK(field).get(60, TimeUnit.MINUTES);
        this.log("主键创建成功: {}", field);
    }
}
